package 堆栈与队列;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 扁平化嵌套列表迭代器 implements Iterator<Integer> {
    private Queue<Integer> queue = new LinkedList<>();

    public 扁平化嵌套列表迭代器(List<NestedInteger> nestedList) {
        for (NestedInteger nestedInteger : nestedList) {
            offerToQueue(queue, nestedInteger);
        }
    }

    private void offerToQueue(Queue<Integer> queue, NestedInteger nestedInteger) {
        if (nestedInteger.isInteger()) {
            queue.offer(nestedInteger.getInteger());
        } else {
            for (NestedInteger nested : nestedInteger.getList()) {
                offerToQueue(queue, nested);
            }
        }
    }

    @Override
    public Integer next() {
        return queue.poll();
    }

    @Override
    public boolean hasNext() {
        return queue.peek() != null;
    }

}

interface NestedInteger {

    // @return true if this NestedInteger holds a single integer, rather than a nested list.
    public boolean isInteger();

    // @return the single integer that this NestedInteger holds, if it holds a single integer
    // Return null if this NestedInteger holds a nested list
    public Integer getInteger();

    // @return the nested list that this NestedInteger holds, if it holds a nested list
    // Return null if this NestedInteger holds a single integer
    public List<NestedInteger> getList();
}
